package com.yc;


import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 点对点的服务端与客户端的聊天
 *   输入输出流.
 * @program: concurrent
 * @description:
 * @author: zy
 * @create: 2022-01-14 15:20
 */
public class Test5_talkServer {

    private static Logger log= Logger.getLogger(Test5_talkServer.class.getName() );

    public static void main(String[] args) {
        ServerSocket ss=null;
        for(  int i=10000;i<65535;i++) {
            try {
                //完成一台时间服务
                ss = new ServerSocket(   i     );
                break;
            } catch (Exception ex) {
                ex.printStackTrace();
                if(   ex instanceof BindException){
                    log.error(     "端口:"+  i  +"已经被占用"  );
                }
            }
        }
        System.out.println(ss.getInetAddress().getHostName() + "启动了,监听了端口号: ****" + ss.getLocalPort() + "***...");

        //客户端通过键盘录入聊天信息
        Scanner keyboard = new Scanner(System.in);
        while(  true ){
            //用了最新的try...resource， 因为 Socket, Scanner, PrintWriter都实现了Closable, 所以都可以放在try中，以自动关闭
            try (
                 Socket s=ss.accept();  //阻塞式方法，监听是否有客户端联上来.



                 //套接字流
                 Scanner clientReader = new Scanner(    s.getInputStream()   );      //  Scanner.nextLine();          按 \n来读取
                 PrintWriter pw = new PrintWriter(      s.getOutputStream()    )    //     PrintWriter.writeLine();   -> 输出数据\n
            ) {
                log.info("客户端:"+ s.getRemoteSocketAddress()+"联接上来了");
                do {
                    String response = clientReader.nextLine();
                    System.out.println("客户端"+  s.getRemoteSocketAddress()+"  对server说:" + response);
                    if ("bye".equalsIgnoreCase(response)) {
                        System.out.println("客户端"+ s.getRemoteSocketAddress()+"主动断开与服务器的联接....");
                        break;
                    }

                    System.out.println("请输入服务器想对客户端"+  s.getRemoteSocketAddress()+" 说的话:");
                    String line = keyboard.nextLine();
                    pw.println(      line           );
                    pw.flush();

                    if ("bye".equalsIgnoreCase(line)) {
                        System.out.println("服务器要求主动断开与客户端"+ s.getRemoteSocketAddress()+"的联接...");
                        break;
                    }

                } while (true);

                System.out.println("在服务端正常结束与客户端"+ s.getRemoteSocketAddress()+"聊天...");




            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }


    }
}
